package com.wanxi.company.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wanxi.common.entity.CompanyModel;
import com.wanxi.common.result.ResultDTO;
import com.wanxi.company.mapper.CompanyMapper;
import com.wanxi.company.service.CompanyService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CompanyServiceImpl implements CompanyService {

    @Autowired
    private CompanyMapper companyMapper;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    @Override
    public ResultDTO add(CompanyModel companyModel) {
        LambdaQueryWrapper<CompanyModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(CompanyModel::getId)
                .eq(companyModel.getName() != null, CompanyModel::getName, companyModel.getName());
        boolean exists = companyMapper.exists(queryWrapper);
        if (exists) {
            return ResultDTO.builder()
                    .code(0)
                    .msg("same name")
                    .count(-1)
                    .data("")
                    .build();
        } else {
            int count = companyMapper.insert(companyModel);
            LambdaQueryWrapper<CompanyModel> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.select(CompanyModel::getId, CompanyModel::getName, CompanyModel::getEnglishName,
                        CompanyModel::getImgHref, CompanyModel::getContent, CompanyModel::getMassage,
                        CompanyModel::getEnable)
                .like(companyModel.getName() != null && companyModel.getName() != "", CompanyModel::getName, companyModel.getName());
            CompanyModel company = companyMapper.selectOne(lambdaQueryWrapper);
            elasticsearchRestTemplate.save(company);
            return ResultDTO.builder()
                    .code(0)
                    .msg("")
                    .count(count)
                    .data("")
                    .build();
        }
    }

    @Override
    public ResultDTO update(CompanyModel companyModel) {
        LambdaQueryWrapper<CompanyModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(CompanyModel::getId)
                .eq(companyModel.getName() != null, CompanyModel::getName, companyModel.getName());
        boolean exists = companyMapper.exists(queryWrapper);
        if (exists) {
            elasticsearchRestTemplate.save(companyModel);
            return ResultDTO.builder()
                    .code(0)
                    .msg("")
                    .count(companyMapper.updateById(companyModel))
                    .data("")
                    .build();

        } else {
            return ResultDTO.builder()
                    .code(0)
                    .msg("have no")
                    .count(-1)
                    .data("")
                    .build();
        }

    }

    @Override
    public ResultDTO delete(CompanyModel companyModel) {
        elasticsearchRestTemplate.delete(companyModel);
        return ResultDTO.builder()
                .code(0)
                .msg("")
                .count(companyMapper.deleteById(companyModel))
                .data("")
                .build();
    }

    @Override
    public ResultDTO findById(CompanyModel companyModel) {
        LambdaQueryWrapper<CompanyModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(CompanyModel::getId, CompanyModel::getName, CompanyModel::getEnglishName,
                        CompanyModel::getImgHref, CompanyModel::getContent, CompanyModel::getMassage,
                        CompanyModel::getEnable)
                .eq(companyModel.getId() != null, CompanyModel::getId, companyModel.getId());
        CompanyModel company = companyMapper.selectOne(queryWrapper);
        return ResultDTO.builder()
                .code(0)
                .msg("")
                .data(company)
                .build();
    }

//
//    @Scheduled(fixedRate = 5000)
//@Scheduled(cron = "0 0 20 * * ?")
    //每天晚上8点
    public void saveToElasticsearch(){
        LambdaQueryWrapper<CompanyModel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(CompanyModel::getId, CompanyModel::getName, CompanyModel::getEnglishName,
                CompanyModel::getImgHref, CompanyModel::getContent, CompanyModel::getMassage,
                CompanyModel::getEnable);
        List<CompanyModel> companyModelList = companyMapper.selectList(queryWrapper);
        elasticsearchRestTemplate.save(companyModelList);
        log.info("看这里的token: {}", "每5秒es更新一次数据");
    }


    public List<CompanyModel> searchAll(CompanyModel companyModel){

        //构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        if (companyModel.getName() != null && !companyModel.getName().isEmpty()) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("name", companyModel.getName()));
        }
        if (companyModel.getEnglishName() != null && !companyModel.getEnglishName().isEmpty()) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("english_name", companyModel.getEnglishName()));
        }
        if (companyModel.getContent() != null && !companyModel.getContent().isEmpty()) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("content", companyModel.getContent()));
        }
        if (companyModel.getMassage() != null && !companyModel.getMassage().isEmpty()) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("massage", companyModel.getMassage()));
        }
        if (companyModel.getEnable() != null && companyModel.getEnable() != -1) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("enable", companyModel.getEnable()));
        }


        queryBuilder.withQuery(boolQueryBuilder);

        queryBuilder.withPageable(PageRequest.of(companyModel.getPage()-1,companyModel.getLimit()));

        // 添加name字段的高亮配置
        HighlightBuilder.Field emailHighlightField = new HighlightBuilder.Field("name");
        emailHighlightField.preTags("<strong>");
        emailHighlightField.postTags("</strong>");
        queryBuilder.withHighlightFields(emailHighlightField);

        // 执行查询
        SearchHits<CompanyModel> searchHits = elasticsearchRestTemplate.search(queryBuilder.build(), CompanyModel.class);

        // 获取查询结果的总条数
        long totalHits = searchHits.getTotalHits();

        // 提取查询结果中的内容部分，并放入列表中返回
        List<CompanyModel> companyModelList = new ArrayList<>();

        for (SearchHit<CompanyModel> searchHit : searchHits) {
            // 从高亮结果中获取name字段的高亮片段
            CompanyModel company = searchHit.getContent();
            List<String> nameHighlights = searchHit.getHighlightField("name");
            if(nameHighlights != null && !nameHighlights.isEmpty()){
                company.setName(nameHighlights.get(0));
            }

            companyModelList.add(company);

        }
        return companyModelList;
    }



    @Override
    public ResultDTO findAll(CompanyModel companyModel) {

//        把数据库数据更新到es
//        saveToElasticsearch();

        //构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();

        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        if (companyModel.getName() != null && !companyModel.getName().isEmpty()) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("name", companyModel.getName()));
        }
        if (companyModel.getEnglishName() != null && !companyModel.getEnglishName().isEmpty()) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("english_name", companyModel.getEnglishName()));
        }
        if (companyModel.getContent() != null && !companyModel.getContent().isEmpty()) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("content", companyModel.getContent()));
        }
        if (companyModel.getMassage() != null && !companyModel.getMassage().isEmpty()) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("massage", companyModel.getMassage()));
        }
        if (companyModel.getEnable() != null && companyModel.getEnable() != -1) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("enable", companyModel.getEnable()));
        }

        queryBuilder.withQuery(boolQueryBuilder);

        queryBuilder.withPageable(PageRequest.of(companyModel.getPage()-1,companyModel.getLimit()));

        // 创建 HighlightBuilder 对象，并配置字段的高亮设置
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        // 添加name字段的高亮配置
        HighlightBuilder.Field nameHighlightField = new HighlightBuilder.Field("name");
//        emailHighlightField.preTags("<strong>");
//        emailHighlightField.postTags("</strong>");
        nameHighlightField.preTags("<font color='red'>");
        nameHighlightField.postTags("</font>");
        highlightBuilder.field(nameHighlightField);

        // 添加content字段的高亮配置
        HighlightBuilder.Field contentHighlightField = new HighlightBuilder.Field("content");
        contentHighlightField.preTags("<font color='red'>");
        contentHighlightField.postTags("</font>");
        highlightBuilder.field(contentHighlightField);


        queryBuilder.withHighlightBuilder(highlightBuilder);

        // 执行查询
        SearchHits<CompanyModel> searchHits = elasticsearchRestTemplate.search(queryBuilder.build(), CompanyModel.class);

        // 获取查询结果的总条数
        long totalHits = searchHits.getTotalHits();

        // 提取查询结果中的内容部分，并放入列表中返回
        List<CompanyModel> companyModelList = new ArrayList<>();

        for (SearchHit<CompanyModel> searchHit : searchHits) {
            // 从高亮结果中获取name字段的高亮片段
            CompanyModel company = searchHit.getContent();
            List<String> nameHighlights = searchHit.getHighlightField("name");
            List<String> contentHighlights = searchHit.getHighlightField("content");
            if(nameHighlights != null && !nameHighlights.isEmpty()){
                company.setName(nameHighlights.get(0));
            }

            if(contentHighlights != null && !contentHighlights.isEmpty()){
                company.setContent(contentHighlights.get(0));
            }



            companyModelList.add(company);
        }

        return ResultDTO.builder()
                .code(0)
                .msg("")
                .count((int) totalHits)
                .data(companyModelList)
                .build();
    }







//    @Override
//    public ResultDTO findAll(CompanyModel companyModel) {
//        LambdaQueryWrapper<CompanyModel> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.select(CompanyModel::getId, CompanyModel::getName, CompanyModel::getEnglishName,
//                        CompanyModel::getImgHref, CompanyModel::getContent, CompanyModel::getMassage,
//                        CompanyModel::getEnable)
//                .like(companyModel.getName() != null && companyModel.getName() != "", CompanyModel::getName, companyModel.getName())
//                .like(companyModel.getEnglishName() != null && companyModel.getEnglishName() != "", CompanyModel::getEnglishName, companyModel.getEnglishName())
//                .like(companyModel.getContent() != null && companyModel.getContent() != "", CompanyModel::getContent, companyModel.getContent())
//                .like(companyModel.getMassage() != null && companyModel.getMassage() != "", CompanyModel::getMassage, companyModel.getMassage())
//                .eq(companyModel.getEnable() != null && companyModel.getEnable() != -1, CompanyModel::getEnable, companyModel.getEnable());
//        IPage<CompanyModel> page = new Page<>(companyModel.getPage(), companyModel.getLimit());
//        IPage<CompanyModel> result = companyMapper.selectPage(page, queryWrapper);
//        return ResultDTO.builder()
//                .code(0)
//                .msg("")
//                .count((int) result.getTotal())
//                .data(result.getRecords())
//                .build();
//    }
}
